import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

const instance = axios.create({
  baseURL: `http://47.114.137.121:8064/xzmg`,
  timeout: 5000,
});

instance.interceptors.request.use(
  function (config) {
    if (config.headers) {
      try {
        let token = localStorage.getItem('token');
        if (token) {
          config.headers.token = JSON.parse(token);
        }
      } catch (error) {}
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function (response) {
    if (response.data.data.records) {
      response.data.data.records.forEach((item) => {
        Object.keys(item).forEach((key) => {
          if (key.includes('time') || key.includes('Time')) {
            item[key] = item[key]?.substring(0, 10);
          }
        });
      });
    }
    console.log(response.data.data, 'reponse.data.data');
    if (response.data.errmsg === 'token error') {
      ElMessage.error('token error');
      localStorage.clear();
      setTimeout(() => {
        window.location.replace('/login');
      }, 1000);
    }
    return response;
  },
  function (error) {
    return Promise.reject(error);
  }
);

interface Data {
  [index: string]: unknown;
}

interface Http {
  get: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>;
  post: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>;
  put: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>;
  patch: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>;
  delete: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>;
}

const http: Http = {
  get(url, data, config) {
    return instance.get(url, {
      params: data,
      ...config,
    });
  },
  post(url, data, config) {
    return instance.post(url, data, config);
  },
  put(url, data, config) {
    return instance.put(url, data, config);
  },
  patch(url, data, config) {
    return instance.patch(url, data, config);
  },
  delete(url, data, config) {
    return instance.delete(url, {
      data,
      ...config,
    });
  },
};

export default http;
